/**  定义电影演员相关的接口 */
const express = require("express");
const router = express.Router();
const Response = require("../utils/Response.js");
const jwt = require('jsonwebtoken')
const SECRET_KEY = 'JWT_SECRET_KEY'

// 引入mysql连接池
const pool = require("../utils/pool");

// 注册用户
router.post("/user-add", (req, res) => {
  let { username, password, phone } = req.body;
  let sql = "select * from user where  username=?";
  pool.query(sql, username, (error, result) => {
    if (error) {
      res.send(Response.error(500, error));
      console.log(error);
      throw error;
    }
    if (result.length == 0) {
      let sql2 = "insert user set ? ";
      let obj = { username, password, phone, avatar: "/user_avatar/moren.jpg" };
      pool.query(sql2, [obj], (error, result) => {
        if (error) {
          res.send(Response.error(500, error));
          throw error;
        }
        res.send(Response.ok());
      });
    } else {
      res.send({ code: 201, msg: "该账号已注册" });
    }
  });
});

// 用户登录
router.post("/user/login", (req, res) => {
  let { username, password:pwd } = req.body;
  let sql = "select * from user where username=?";
  pool.query(sql, username, (error, result) => {
    if (error) {
      res.send(Response.error(500, error));
      throw error;
    }
    if (result.length == 0) {
      res.send({ code: 1001, msg: "用户名不存在" });
    } else {
      const { uid, username, password,avatar } = result[0];
      if (pwd == password) {
        let payload = {id: uid, 
          nickname: username
        }
        let token = jwt.sign(payload, SECRET_KEY, {expiresIn: '1d'})
        // 返回user对象与token字符串
        let user = result[0]
        user.password = undefined
        res.send(Response.ok({user, token}));
      } else {
        res.send({ code: 201, msg: "密码错误" });
      }
    }
  });
});


// 按电影id查询评论
router.get('/comments',(req,res)=>{
  let {vid} = req.query
  let sql = 'select * from comment where vid = ?'
  pool.query(sql,[vid],(error,result)=>{
    if (error) {
      res.send(Response.error(500, error));
      throw error;
    }
    res.send(Response.ok(result))
  })
})

// 将router对象导出
module.exports = router;
